package net.xdclass.component;

import net.xdclass.strategy.ShardingDBConfig;
import net.xdclass.strategy.ShardingTableConfig;
import net.xdclass.util.CommonUtil;
import org.springframework.stereotype.Component;

@Component
public class ShortLinkComponent {
    /**
     * 创建短链
     *
     * @param originalUrl
     * @return db编码+6位短链编码
     */
    public String createShortLinkCode(String originalUrl) {
        long murmur32 = CommonUtil.murmurHash32(originalUrl);
        //转62进制
        String code = encodeToBase62(murmur32);
        String shortLinkCode = ShardingDBConfig.getRandomDBPrefix(code) + code + ShardingTableConfig.getTableRandomPrefix(code);
        return shortLinkCode;
    }

    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 10进制转62进制
     *
     * @param num
     * @return
     */
    private static String encodeToBase62(long num) {
        //StringBuffer：线程安全;    StringBuilder：线程不安全
        StringBuffer sb = new StringBuffer();
        do {
            int i = (int) (num % 62);
            sb.append(CHARS.charAt(i));
            num /= 62;
            // num = num/ 62;
        } while (num > 0);

        String value = sb.reverse().toString();
        return value;
    }
}
